<script setup lang="ts" name="PaneFormSource">
import { mapState } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import {
  isFormSupported,
  isFormBusinessKey,
  getFormTypeValue,
  setFormTypeValue,
  getFormRefValue,
  setFormRefValue,
  getFormRefBindingValue,
  setFormRefBindingValue,
  getFormRefVersionValue,
  setFormRefVersionValue,
  getFormKeyValue,
  setFormKeyValue,
  getFormTypeList,
  getBindingList,
  getFormBusinessKeyValue,
  setFormBusinessKeyValue,
  getBusinessKeyOptions,
  getFormFieldsTypeObject,
  getFormDataValue,
  addFormField,
  editFormField,
  removeFormField
} from '../../utils/formSource'
import EventEmitter from '@/utils/EventEmitter'
import FormFieldsDrawer from './components/FormFieldsDrawer.vue'
import useMessageBox from '@/hooks/useMessageBox'
import { cloneDeep } from 'lodash-es'

const { messageBox } = useMessageBox()

const form = ref({
  type: ''
})
const formFields = ref([])
const businessKeyList = ref([])
const formTypeList = ref([])
const bindingList = ref([])
const formFieldsType = ref(null)
const FormFieldsDrawerRef = ref(null)
const editIndex = ref(-1)

const isBusinessKeyVisible = ref(false)

const mapStates = computed(() => {
  return mapState(useModelerStore, ['getActive'])
})

const setFormType = (value: string | undefined) => {
  isBusinessKeyVisible.value = isFormBusinessKey(mapStates.value.getActive())
  setFormTypeValue(mapStates.value.getActive(), value)
}

const setFormRef = (value: string | undefined) => {
  setFormRefValue(mapStates.value.getActive(), value)
}

const setFormRefBinding = (value: string | undefined) => {
  setFormRefBindingValue(mapStates.value.getActive(), value)
}

const setFormRefVersion = (value: string | undefined) => {
  setFormRefVersionValue(mapStates.value.getActive(), value)
}

const setFormKey = (value: string | undefined) => {
  setFormKeyValue(mapStates.value.getActive(), value)
}

const setFormBusinessKey = (value: string | undefined) => {
  setFormBusinessKeyValue(mapStates.value.getActive(), value)
}

const add = () => {
  editIndex.value = -1
  FormFieldsDrawerRef.value.showDrawer()
}

const edit = (row, index) => {
  editIndex.value = index
  FormFieldsDrawerRef.value.showDrawer(row)
}

const deleteRow = (index) => {
  const msg = '确认<span>删除</span>该表单字段吗？'
  const msgTips = ''
  messageBox('danger', true, msg, msgTips, () => {
    removeFormField(mapStates.value.getActive(), formFields.value[index])
  })
}

const formFieldsChange = (v) => {
  console.log(v, '表单字段')
  if (editIndex.value === -1) {
    addFormField(mapStates.value.getActive(), v)
  } else {
    editFormField(mapStates.value.getActive(), v, editIndex.value)
  }
}

const initData = () => {
  form.value.type = getFormTypeValue(mapStates.value.getActive())
  isBusinessKeyVisible.value = isFormBusinessKey(mapStates.value.getActive())
  if (isBusinessKeyVisible.value) {
    businessKeyList.value = getBusinessKeyOptions(mapStates.value.getActive())
  }
  if (form.value.type === 'formRef') {
    form.value['formRef'] = getFormRefValue(mapStates.value.getActive())
    form.value['formRefBinding'] = getFormRefBindingValue(mapStates.value.getActive())
    form.value['formRefVersion'] = getFormRefVersionValue(mapStates.value.getActive())
  } else if (form.value.type === 'formKey') {
    form.value['formKey'] = getFormKeyValue(mapStates.value.getActive())
  } else if (form.value.type === 'formData') {
    form.value['businessKey'] = getFormBusinessKeyValue(mapStates.value.getActive())
    formFields.value = markRaw(getFormDataValue(mapStates.value.getActive()))
    form.value['fields'] = cloneDeep(formFields.value)
    console.log(form.value['fields'], '表单数据获取')
  }
}

const eventEmitterListener = () => {
  if (isFormSupported(mapStates.value.getActive())) {
    initData()
  }
}

onBeforeUnmount(() => {
  EventEmitter.removeListener('element-update', eventEmitterListener)
})

onMounted(() => {
  formTypeList.value = getFormTypeList()
  bindingList.value = getBindingList()
  formFieldsType.value = getFormFieldsTypeObject()
  initData()
  EventEmitter.on('element-update', eventEmitterListener)
})
</script>

<template>
  <el-collapse-item name="form-source">
    <template #title>
      <div class="collapse-header">
        <svg-icon icon="ri:file-code-fill"></svg-icon>
        <h2>表单</h2>
      </div>
    </template>
    <el-form-item label="类型">
      <el-select v-model="form.type" clearable @change="setFormType">
        <el-option v-for="item in formTypeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <template v-if="form.type === 'formRef'">
      <el-form-item label="表单引用">
        <el-input v-model="form['formRef']" @change="setFormRef" />
      </el-form-item>
      <el-form-item label="绑定版本">
        <el-select v-model="form['formRefBinding']" @change="setFormRefBinding">
          <el-option v-for="item in bindingList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form['formRefBinding'] === 'version'" label="版本号">
        <el-input v-model="form['formRefVersion']" @change="setFormRefVersion" />
      </el-form-item>
    </template>
    <template v-if="form.type === 'formKey'">
      <el-form-item label="表单键">
        <el-input v-model="form['formKey']" @change="setFormKey" />
      </el-form-item>
    </template>
    <template v-if="form.type === 'formData'">
      <el-form-item v-if="isBusinessKeyVisible" label="业务标识">
        <el-select v-model="form['businessKey']" @change="setFormBusinessKey">
          <el-option v-for="item in businessKeyList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <div class="field-content">
        <el-divider>
          <div class="divider-panel">
            <svg-icon icon="ri:code-s-slash-line"></svg-icon>
            <span>表单字段</span>
          </div>
        </el-divider>
        <el-table :data="form['fields']" border>
          <el-table-column type="index" label="序号" width="60" fixed="left" />
          <el-table-column prop="id" label="编号" show-overflow-tooltip />
          <el-table-column prop="label" label="名称" show-overflow-tooltip />
          <el-table-column prop="type" label="类型" show-overflow-tooltip :formatter="row => formFieldsType[row.type] ? formFieldsType[row.type] : '自定义'" />
          <el-table-column prop="defaultValue" label="默认值" show-overflow-tooltip />
          <el-table-column prop="operate" label="操作" width="110" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" icon="Edit" circle @click="edit(scope.row, scope.$index)"></el-button>
              <el-button type="danger" icon="Delete" circle @click="deleteRow(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button class="add" type="primary" icon="Plus" @click="add">添加字段</el-button>
        <FormFieldsDrawer ref="FormFieldsDrawerRef" @save="formFieldsChange"></FormFieldsDrawer>
      </div>
    </template>
  </el-collapse-item>
</template>

<style scoped lang="scss">
.el-collapse-item {
  :deep(.el-collapse-item__header) {

    .collapse-header {
      display: flex;
      flex: 1;
      align-items: center;
      padding: 0 12px;

      .el-icon {
        margin-right: 6px;
        font-size: 20px !important;
      }

      h2 {
        font-weight: bold;
        font-size: 14px;
      }

      .el-button {
        margin-left: 12px;
      }
    }

    .el-icon {
      font-size: 18px;
    }
  }

  :deep(.el-collapse-item__content) {
    padding-right: 12px;
    padding-bottom: 12px;
    padding-left: 12px;
  }
}

.field-content {

  .el-button.add {
    width: 100%;
    margin: 12px 0 0;
  }
}

.divider-panel {
  display: flex;
  align-items: center;

  span {
    margin-left: 6px;
  }
}

.el-form-item {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;

    .el-button.add {
      width: 100%;
      margin: 12px 0 0;
    }
  }
}
</style>
